import axios from "axios";
import qs from "qs";
import { Message, Loading, Alert } from "element-ui";
import router from "../router";
import store from "../store";

export default function $axios(options) {
  return new Promise((resolve, reject) => {
    var loading = null;
    let timeOut = 30000;
    let timer = setTimeout(() => {
      loading = options.noLoading
        ? null
        : Loading.service({
            // target: '.loadDom',
            target: ".middleContainer",
            lock: true,
            background: "rgba(255, 255, 255, 0.5)",
          });
    }, 600);
    //工作票办理-工单开票查询数据，延长等待时间
    if (options.url == "/eam-service-order/orderAll/queryPageListNoMerge") {
      timeOut = 60000;
    }
    //下载打印控件
    if (options.url == "/eam-common-web/printConfig/downloadPrint") {
      timeOut = 600000;
    }
    //上传文件时，延长等待时间
    if (
      options.headers &&
      options.headers["Content-Type"].indexOf("multipart/form-data") !== -1
    ) {
      timeOut = 60000 * 10;
    }
    const instance = axios.create({
      timeout: timeOut,
      withCredentials: false,
      baseURL: process.env.VUE_APP_BASEURL,
    });
    /* 对工单模块作业指导书查询附件时修改GDH_WATER_TOKEN */
    let isorderBookList = false;
    if (options.url == "/eam-common-web/attachment/attachmentList") {
      let orderType =
        options.params.type === undefined ? null : options.params.type;
      //需要跨库查询附件时
      if (orderType && orderType == "other") {
        isorderBookList = true;
      }
    }
    if (
      options.url == "/eam-service-order/experiment/execute/getPrintTemplate" ||
      options.url ==
        "/eam-service-order/experiment/execute/previewExperiment.htm"
    ) {
      isorderBookList = true;
    }
    //请求
    instance.interceptors.request.use(
      (config) => {
        if (JSON.stringify(store.getters.currentInfo) != "{}") {
          config.headers.common["DYNAMIC_DATA_SOURCE"] =
            store.getters.currentInfo.currDs;
          config.headers.common["DYNAMIC_AGENT_ORG"] =
            store.getters.currentInfo.currOrg;
          config.headers.common["DYNAMIC_LEADER"] =
            store.getters.currentInfo.currLeader;
          if (store.getters.currentInfo.currLeaderOrg) {
            config.headers.common["DYNAMIC_LEADER_ORG"] =
              store.getters.currentInfo.currLeaderOrg;
          }
        } else {
          if (localStorage.getItem("currDs")) {
            config.headers.common["DYNAMIC_DATA_SOURCE"] = localStorage.getItem(
              "currDs"
            );
          }
          if (localStorage.getItem("currOrg")) {
            config.headers.common["DYNAMIC_AGENT_ORG"] = localStorage.getItem(
              "currOrg"
            );
          }
          if (localStorage.getItem("currLeader")) {
            config.headers.common["DYNAMIC_LEADER"] = localStorage.getItem(
              "currLeader"
            );
          }
          if (localStorage.getItem("currLeaderOrg")) {
            config.headers.common["DYNAMIC_LEADER_ORG"] = localStorage.getItem(
              "currLeaderOrg"
            );
          }
        }
        if (isorderBookList) {
          config.headers.common["DYNAMIC_DATA_SOURCE"] = "_default";
        }
        if (localStorage.getItem("GDH_WATER_TOKEN")) {
          config.headers.common["jwt_token"] =
            localStorage.getItem("GDH_WATER_TOKEN") || "";
        }
        config.headers.common["OUT_ORG"] = localStorage.getItem("OUT_ORG") || 0;
        if (config.method === "get") {
          config.paramsSerializer = function(params) {
            return qs.stringify(params, {
              arrayFormat: "indices",
              allowDots: true,
            });
          };
        }
        if (
          config.url ===
          "/eam-service-order/experiment/execute/getPrintTemplate"
        ) {
        }
        if (config.responseType === "blob") {
          config.headers.common["responseType"] = "blob";
        }
        //ie缓存问题
        if (config.url.indexOf("?") != -1) {
          config.url = config.url + "&" + Math.floor(Math.random() * 100000);
        } else {
          config.url = config.url + "?" + Math.floor(Math.random() * 100000);
        }
        return config;
      },
      (error) => {
        if (
          error.code === "ECONNABORTED" &&
          error.message.indexOf("timeout") !== -1
        ) {
          console.log(
            "根据你设置的timeout/真的请求超时 判断请求现在超时了，你可以在这里加入超时的处理方案"
          );
          // return service.request(originalRequest);//例如再重复请求一次
        }
        Message({
          showClose: true,
          message: `错误提示:${error}`,
          type: "error",
        });
        return Promise.reject(error);
      }
    );
    // response 拦截器
    instance.interceptors.response.use(
      (response) => {
        if (response.headers.jwt_token) {
          localStorage.setItem("GDH_WATER_TOKEN", response.headers.jwt_token);
        }
        if (response.headers.skip_sign) {
          localStorage.setItem("SKIP_SIGN", response.headers.skip_sign);
        }
        if (response.headers.dynamic_data_source) {
          localStorage.setItem("currDs", response.headers.dynamic_data_source);
        }
        if (response.headers.dynamic_agent_org) {
          localStorage.setItem("currOrg", response.headers.dynamic_agent_org);
        }
        if (!response.data.hasOwnProperty("code")) {
          return response.data;
        }
        switch (response.data.code) {
          case 200:
            return response.data;
          case 10000:
            localStorage.clear();
            router.push("/login");
          default:
            Message({
              showClose: true,
              message: `错误提示: ${response.data.description}`,
              type: "error",
            });
            throw response.data.description;
        }
      },
      (err, response) => {
        if (err && err.response) {
          switch (err.response.status) {
            case 302:
              window.location.href = err.response.headers.redirecturl;
            case 400:
              err.message = "请求错误";
              break;
            case 401:
              err.message = "未授权，请登录";
              break;
            case 403:
              err.message = "拒绝访问";
              break;
            case 404:
              err.message = `请求地址出错: ${err.response.config.url}`;
              break;
            case 408:
              err.message = "请求超时";
              break;
            case 500:
              let mes = err.response.data.description || null;
              if (mes) {
                err.message = mes;
              } else {
                err.message = "服务器内部错误";
              }
              break;
            case 501:
              err.message = "服务未实现";
              break;

            case 502:
              err.message = "网关错误";
              break;

            case 503:
              err.message = "服务不可用";
              break;

            case 504:
              err.message = "网关超时";
              break;

            case 505:
              err.message = "HTTP版本不受支持";
              break;
            case 505:
              err.message = "HTTP版本不受支持";
              break;

            default:
          }
        }

        if (err.response.status == 302) {
          return Promise.reject(err);
        } else {
          if (
            err.response.data.code == 5001 ||
            err.response.data.code == 5002
          ) {
            Message({
              showClose: true,
              message: err.message,
              type: "waring",
            });
          } else {
            Message({
              showClose: true,
              message: `错误提示: ${
                err.message.includes("timeout") ? "请求超时" : err
              }`,
              type: "error",
            });
          }
        }
        return Promise.reject(err);
      }
    );
    //请求处理
    instance(options)
      .then((res) => {
        resolve(res);
        clearTimeout(timer);
        if (loading) {
          loading.close();
        }
        return false;
      })
      .catch((error) => {
        reject(error);
        clearTimeout(timer);
        if (loading) {
          loading.close();
        }
      });
  });
}
